// popup.js

const GLOBAL_STORAGE_KEY = 'ruleActEnabled';
// 切换为滑块容器的 ID
const toggleContainer = document.getElementById('globalToggle');
const statusLabel = document.getElementById('statusLabel');

// 1. 读取当前状态并设置 UI
chrome.runtime.sendMessage({ action: 'GET_GLOBAL_STATE' }, (response) => {
    // 默认启用
    const isEnabled = response.isEnabled;

    // 初始化滑块的 class
    if (isEnabled) {
        toggleContainer.classList.add('on');
    }
    updateLabel(isEnabled);
});

// 2. 监听用户交互
toggleContainer.addEventListener('click', () => {
    // 切换当前状态
    const isEnabled = !toggleContainer.classList.contains('on');

    // 立即更新 UI (提供即时反馈)
    if (isEnabled) {
        toggleContainer.classList.add('on');
    } else {
        toggleContainer.classList.remove('on');
    }

    // 通知 Service Worker 切换状态
    chrome.runtime.sendMessage({ action: 'TOGGLE_GLOBAL_STATE', isEnabled: isEnabled }, () => {
        updateLabel(isEnabled);
    });
});

function updateLabel(isEnabled) {
    statusLabel.textContent = isEnabled ? '已启用' : '已禁用';
    statusLabel.style.color = isEnabled ? 'green' : 'red';
}